<template>
    <view class="container">
        <!-- 搜索框 -->
        <view class="search-bar">
            <u-search v-model="searchQuery" placeholder="搜索合同订单..." />
        </view>

        <!-- 合同订单消息列表 -->
        <view class="order-list">
            <view v-for="(order, index) in filteredOrders" :key="order.contractId" class="order-item"
                @click="toggleReadStatus(order)">
                <view class="order-header">
                    <text class="order-id">合同编号: {{ order.contractId }}</text>
                    <text class="order-date">{{ formatDate(order.createTime) }}</text>
                </view>
                <view class="order-body"> 
                    <text class="order-title">{{ order.createBy }}</text>
                    <br>
                    <!-- 显示描述的前10个字符，后续用省略号表示 -->
                    <text class="order-description">{{ truncateText(order.contractDetails, 20) }}</text>
                </view>
                <!-- 已读/未读状态 -->
                <view class="order-status">
                    <text :class="order.read === 1 ? 'read' : 'unread'">{{ order.read = 1 ? '已读' : '未读' }}</text>
                </view>
            </view>
        </view>
        <!-- 下拉加载提示 -->
        <view v-if="isLoading" class="loading">加载中...</view>
        <view v-if="noMore" class="no-more">没有更多数据了</view>
    </view>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useUserStore } from '@/stores/user.js';
import { contractdata } from '@/common/api.js';

export default {
  setup() {
    const userStore = useUserStore(); // 获取用户数据
    const searchQuery = ref(''); // 搜索框输入
    const orders = ref([]); // 合同订单数据
    const page = ref({
      size: 6, // 每页大小
      currentPage: 1, // 当前页
    });
    const noMore = ref(false); // 是否有更多数据
    const isLoading = ref(false); // 是否正在加载数据

    // 计算属性，返回过滤后的合同订单列表
    const filteredOrders = computed(() => {
      if (searchQuery.value) {
        return orders.value.filter(
          (order) =>
            order.createBy.includes(searchQuery.value) ||
            String(order.contractId).includes(searchQuery.value)
        );
      } else {
        return orders.value;
      }
    });
    // 日期格式化函数
    const formatDate = (timestamp) => {
      if (!timestamp) return ''; // 处理空值情况
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以需要 +1
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };
    // 截取文本的函数，截取前 num 个字符并在后面添加省略号
    const truncateText = (text, num) => {
      if (!text) {
        return ''; // 如果 text 是 undefined 或 null，返回空字符串
      }
      if (text.length > num) {
        return text.slice(0, num) + '...';
      }
      return text;
    };

    // 加载合同数据
    const loadContractData = () => {
      if (isLoading.value || noMore.value) return; // 防止重复加载或在没有更多数据时加载

      isLoading.value = true;

      const params = {
        userId: userStore.userId, // 获取用户 ID
        size: page.value.size,
        currentPage: page.value.currentPage,
      };

      contractdata(params)
        .then((res) => {
          if (res && res.data) {
            orders.value = [...orders.value, ...res.data]; // 添加新数据到现有列表
            if (res.data.length < page.value.size) {
              noMore.value = true; // 标记没有更多数据
            }
          }
        })
        .catch((error) => {
          console.error("请求失败:", error);
        })
        .finally(() => {
          isLoading.value = false;
        });
    };

    // 切换已读/未读状态
    const toggleReadStatus = (order) => {
      order.read = 1; // 设置为已读
      wx.redirectTo({
        url: `/pages/contract/Detail?id=${order.contractId}`,
      });
    };

    // 页面初始化时加载数据
    onMounted(() => {
      loadContractData();
    });

    // 微信小程序的生命周期函数：触底加载更多
    const onReachBottom = () => {
      if (!noMore.value) {
        page.value.currentPage += 1; // 增加页码
        loadContractData(); // 加载更多数据
      }
    };

    // 返回所有需要在模板中使用的变量和方法
    return {
      searchQuery,
      orders,
      page,
      noMore,
      isLoading,
      filteredOrders,
      truncateText,
      loadContractData,
      toggleReadStatus,
      onReachBottom,
	  formatDate,
    };
  },

  // 微信小程序的生命周期函数：触底加载更多
  onReachBottom() {
    this.onReachBottom();
  },
};
</script>




<style scoped>
	.container {
		padding: 20px;
	}
	.loading,
	.no-more {
		text-align: center;
		padding: 16px;
	}
	/* 搜索框样式 */
	.search-bar {
		margin-bottom: 20px;
		display: flex;
		justify-content: center;
	}

	.order-list {
		display: flex;
		flex-direction: column;
		gap: 15px;
	}

	.order-item {
		background-color: #ffffff;
		padding: 15px;
		border-radius: 8px;
		box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
		cursor: pointer;
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10px;
	}

	.order-id {
		font-weight: bold;
		color: #333;
	}

	.order-date {
		color: #888;
		font-size: 14px;
	}

	.order-body {
		margin-top: 10px;
	}

	.order-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 5px;
	}

	.order-description {
		color: #555;
		font-size: 14px;
	}

	.order-status {
		margin-top: 10px;
		text-align: right;
	}

	.read {
		color: green;
		font-weight: bold;
	}

	.unread {
		color: red;
		font-weight: bold;
	}
</style>